import React, { useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import { Image, Icon } from 'components/atoms';
import { SectionHeader } from 'components/molecules';
import { HeroShaped } from 'components/organisms';
import { setLoading } from 'redux/actions/LoadingActions';
import { setCallbackError } from 'redux/actions/LoadingActions';
import { useDispatch, useSelector } from 'react-redux';
import {
  PayPalScriptProvider,
  PayPalButtons,
  usePayPalScriptReducer
} from "@paypal/react-paypal-js";
import { Typography, ListItem, Divider, List, Grid } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
import { callPostApi } from 'utils/networking';

const useStyles = makeStyles(theme => ({
  root: {
    '& .hero-shaped': {
      borderBottom: 0,
    },
    '& .hero-shaped__wrapper': {
      [theme.breakpoints.up('md')]: {
        minHeight: `calc(100vh - ${theme.mixins.toolbar['@media (min-width:600px)'].minHeight}px)`,
      },
    },
  },
  formContainer: {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    [theme.breakpoints.down('sm')]: {
      maxWidth: 500,
      margin: `0 auto`,
    },
  },
  image: {
    objectFit: 'cover',
  },
  featureCheck: {
    marginRight: theme.spacing(1),
  },
}));

const ButtonWrapper = ({ type, subscriptionItem, profileData }) => {
  const [{ options }, dispatch] = usePayPalScriptReducer();
  const history = useHistory();
  const mdispatch = useDispatch();

  const paypalSubscribe = (data, actions) => {
    console.log('data', JSON.stringify(data));
    console.log('actions', JSON.stringify(actions));

    return actions.subscription
      .create({ plan_id: subscriptionItem.plan_id })
      .then((orderId) => {
        console.log('orderId', orderId);
        return orderId;
      });
  }

  const paypalOnError = (err) => {
    alert("Error occurred, You've already subscribed or please try again later");
    console.log("Error", err);
  }

  const paypalOnApprove = (data, detail) => {
    console.log('data', JSON.stringify(data));
    console.log('detail', JSON.stringify(detail));
    postSubscriptionStatus(data);
  };

  const getAddress = (address) => {
    try {
      return address.address_line_1 +
        ' ' + address.admin_area_2 +
        ' ' + address.admin_area_1 +
        ' ' + address.postal_code +
        ' ' + address.country_code

    } catch (err) {
      console.log(err);
    }

    return '';
  }

  const getNumber = (phone) => {
    if (phone && phone.phone_number
      && phone.phone_number.national_number) {
      return phone.phone_number.national_number;

    } else {
      return '';
    }
  }

  const getName = (name) => {
    try {
      return name.given_name + ' ' + name.surname

    } catch (err) {
      console.log(err);
    }
  }

  const postSubscriptionStatus = (data) => {
    if (data.orderID && data.subscriptionID) {
      const params = {
        user_id: profileData.id,
        subscription_item_id: subscriptionItem.id,
        order_id: data.orderID,
        subscription_id: data.subscriptionID,
        facilitator_access_token: data.facilitatorAccessToken
      }
      callPostApi('subscription/subscribe', params, dispatch, (data) => {
        mdispatch(setCallbackError({
          title: 'Success',
          content: 'Successfully subscribed'
        }));

        if (subscriptionItem.podcast_id && subscriptionItem.podcast_id > 0) {
          history.push(`podcast/${subscriptionItem.podcast_id}`)
        }
        else {
          history.push(`artist/${subscriptionItem.artist_id}`)
        }

        history.go(0)
      })
    }
    else {
      alert("Unknow error occurred, please contact us");
    }
  }

  useEffect(() => {
    dispatch({
      type: "resetOptions",
      value: {
        ...options,
        intent: "subscription",
      },
    });
  }, [type]);

  return (<PayPalButtons
    createSubscription={paypalSubscribe}
    onApprove={paypalOnApprove}
    catchError={paypalOnError}
    onError={paypalOnError}
    onCancel={paypalOnError}
    style={{
      label: "subscribe",
    }}
  />);
}

const Subscription = () => {
  const classes = useStyles();
  const history = useHistory();
  const profileData = useSelector((state) => state.auth.profileData)
  const mSubscriptionItem = useSelector((state) => state.searchArtists.selectedSubscription)
  const features = [mSubscriptionItem.feature_1, mSubscriptionItem.feature_2, mSubscriptionItem.feature_3, mSubscriptionItem.feature_4, mSubscriptionItem.feature_5]

  useEffect(() => {
    if (!profileData) {
      history.replace('signin');
      return;
    }
    if (!mSubscriptionItem || !mSubscriptionItem.id) {
      history.goBack();
    }
  }, []);

  return (
    <div className={classes.root}>
      <HeroShaped
        leftSide={
          <div className={classes.formContainer}>
            <SectionHeader
              title={mSubscriptionItem.title ? mSubscriptionItem.title : ''}
              subtitle={mSubscriptionItem.sub_title ? mSubscriptionItem.sub_title : ''}
              titleProps={{
                variant: 'h3',
              }}
            />
            <PayPalScriptProvider
              options={{
                "client-id": process.env.REACT_APP_PAYPAL_CLIENT_ID,
                components: "buttons",
                intent: "subscription",
                vault: true,
              }}
            >
              <ButtonWrapper
                type="subscription"
                subscriptionItem={mSubscriptionItem}
                profileData={profileData} />
            </PayPalScriptProvider>
            {features && (
              <Grid item xs={12} className="card-pricing-standard__feature-wrapper">
                <List className="card-pricing-standard__feature-list">
                  {features.map((item, index) => item && (
                    <ListItem
                      key={index}
                      disableGutters
                      className="card-pricing-standard__feature-list-item"
                    >
                      <div
                        className={clsx(
                          'card-pricing-standard__feature-check',
                          classes.featureCheck,
                        )}
                      >
                        <Icon
                          fontIconClass="far fa-check-circle"
                        />
                      </div>
                      <Typography
                        variant="h6"
                        noWrap
                        className="card-pricing-standard__feature-title"
                      >
                        {item}
                      </Typography>
                    </ListItem>
                  ))}
                </List>
              </Grid>
            )}
          </div>
        }
        rightSide={
          <Image
            src="https://assets.maccarianagency.com/the-front/photos/account/cover-2.png"
            className={classes.image}
            lazy={false}
          />
        }
      />
    </div>
  );
};

export default Subscription;

